import pandas as pd
from sklearn.linear_model import LinearRegression

def independence_weight(df: pd.DataFrame, columns: list) -> pd.Series:
    # 计算每个变量被移除后的模型预测能力损失
    r_squared_scores = {}
    for target_col in columns:
        # 构建特征矩阵（仅包含其他变量）
        other_columns = [c for c in columns if c != target_col]
        X = df[other_columns]
        y = df[target_col]
        
        # 确保特征矩阵非空或无完全相关性时进行拟合
        if X.empty:
            r_squared = 0.0
        else:
            try:
                model = LinearRegression().fit(X, y)
                r_squared = model.score(X, y)
            except ValueError:  # 处理多重共线性可能引发的数值问题
                r_squared = 0.0  # 设为默认值
        
        r_squared_scores[target_col] = 1 - r_squared

    # 计算权重
    r_squared_total = sum(r_squared_scores.values()) or 0.0  # 避免除以0的情况
    return pd.Series([v / r_squared_total for v in r_squared_scores.values()], 
                    index=r_squared_scores.keys(), name='Independence_Weight')
